package com.amazon.shop.service.impl;

import com.amazon.shop.aop.SystemLog;
import com.amazon.shop.constant.ReturnConstant;
import com.amazon.shop.entity.OperationLog;
import com.amazon.shop.entity.auth.Roles;
import com.amazon.shop.entity.auth.Users;
import com.amazon.shop.entity.auth.UsersRoles;
import com.amazon.shop.exception.CustomException;
import com.amazon.shop.mapper.OperationLogMapper;
import com.amazon.shop.service.OperationLogService;
import com.amazon.shop.service.RolesService;
import com.amazon.shop.service.UsersRolesService;
import com.amazon.shop.service.UsersService;
import com.amazon.shop.utils.AreaUtils;
import com.amazon.shop.utils.HttpContextUtils;
import com.amazon.shop.utils.IPUtils;
import com.amazon.shop.vo.AddressVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 郭非
 * @since 2021-06-12
 */
@Service
public class OperationLogServiceImpl extends ServiceImpl<OperationLogMapper, OperationLog> implements OperationLogService {
    @Resource
    private UsersRolesService usersRolesService;
    @Resource
    private RolesService rolesService;
    @Resource
    private UsersService usersService;

    /**
     * 保存日志(String类型)
     *
     * @param joinPoint
     * @param id
     * @param salesman
     */
    @Override
    public void saveOperationLog(ProceedingJoinPoint joinPoint, String id, String salesman) {
        try {
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = signature.getMethod();
            SystemLog systemLog = method.getAnnotation(SystemLog.class);
            if (systemLog != null) {
                String value = systemLog.value();
                OperationLog operationLog = new OperationLog();
                operationLog.setType(value);
                //获取ip
                HttpServletRequest httpServletRequest = HttpContextUtils.getHttpServletRequest();
                String ip = IPUtils.getIpAddr(httpServletRequest);

                if (!StringUtils.isEmpty(ip)) {
                    operationLog.setIp(ip);

                    //根据ip设置地域
                    try {
                        AddressVo addressVo = AreaUtils.getAddressByIp(ip, "n9sXQjKmGXhZPylmtVTwKjzbDysw2OKi");
                        if (addressVo != null) {
                            String address = addressVo.getContent().getAddress();
                            if (address != null) {
                                operationLog.setArea(address);
                            }
                        }
                    }finally {

                    }
                }
                //设置数据库表编号
                operationLog.setTableId(id);
                //设置业务员
                operationLog.setSalesman(salesman);


                //通过业务员名字业务员编号
                QueryWrapper<Users> usersQueryWrapper = new QueryWrapper<>();
                usersQueryWrapper.eq("real_name", salesman);
                Users users = usersService.getOne(usersQueryWrapper);
                String userId = users.getUserId();

                //通过业务员编号查询角色编号
                QueryWrapper<UsersRoles> usersRolesQueryWrapper = new QueryWrapper<>();
                usersRolesQueryWrapper.eq("user_id", userId);
                UsersRoles usersRoles = usersRolesService.getOne(usersRolesQueryWrapper);
                String roleId = usersRoles.getRoleId();

                //通过角色编号查询所在部门
                Roles roles = rolesService.getById(roleId);
                String apartmentName = roles.getApartmentName();
                //设置部门
                operationLog.setDepartment(apartmentName);
                //批量更新或保存日志信息
                this.save(operationLog);
            }
        } catch (Exception e) {
            throw new CustomException(ReturnConstant.SAVE_LOG_ERROR_CODE
                    , ReturnConstant.SAVE_LOG_ERROR_MESSAGE);
        }
    }

    /**
     * 批量保存日志
     *
     * @param joinPoint
     * @param idList
     * @param salesman
     */
    @Override
    public void saveOperationLogBatch(ProceedingJoinPoint joinPoint, List<String> idList, String salesman) {
        try {
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = signature.getMethod();
            SystemLog systemLog = method.getAnnotation(SystemLog.class);
            if (systemLog != null) {
                List<OperationLog> operationLogList = idList.stream().map((id) -> {
                    String value = systemLog.value();
                    OperationLog operationLog = new OperationLog();
                    operationLog.setType(value);

                    //获取ip
                    HttpServletRequest httpServletRequest = HttpContextUtils.getHttpServletRequest();
                    String ip = IPUtils.getIpAddr(httpServletRequest);
                    if (!StringUtils.isEmpty(ip)) {
                        operationLog.setIp(ip);
                        AddressVo addressVo = AreaUtils.getAddressByIp(ip, "n9sXQjKmGXhZPylmtVTwKjzbDysw2OKi");
                        if (addressVo != null) {
                            String address = addressVo.getContent().getAddress();
                            operationLog.setArea(address);
                        }
                    }

                    //设置数据库表编号
                    operationLog.setTableId(id);
                    //设置业务员
                    operationLog.setSalesman(salesman);

                    //通过业务员名字业务员编号
                    QueryWrapper<Users> usersQueryWrapper = new QueryWrapper<>();
                    usersQueryWrapper.eq("real_name", salesman);
                    Users users = usersService.getOne(usersQueryWrapper);
                    String userId = users.getUserId();

                    //通过业务员编号查询角色编号
                    QueryWrapper<UsersRoles> usersRolesQueryWrapper = new QueryWrapper<>();
                    usersRolesQueryWrapper.eq("user_id", userId);
                    UsersRoles usersRoles = usersRolesService.getOne(usersRolesQueryWrapper);
                    String roleId = usersRoles.getRoleId();

                    //通过角色编号查询所在部门
                    Roles roles = rolesService.getById(roleId);
                    String apartmentName = roles.getApartmentName();
                    //设置部门
                    operationLog.setDepartment(apartmentName);
                    return operationLog;
                }).collect(Collectors.toList());
                //批量更新或保存日志信息
                this.saveOrUpdateBatch(operationLogList);
            }
        } catch (Exception e) {
            throw new CustomException(ReturnConstant.SAVE_LOG_ERROR_CODE
                    , ReturnConstant.SAVE_LOG_ERROR_MESSAGE);
        }
    }
}
